import { Controller, Get, Post, Put, Delete, Param, Body, UseGuards, BadRequestException } from '@nestjs/common';
import { ArticleService } from './article.service';
import { Article } from './article.entity';
import { JwtHttpGuard } from '../auth/jwt-http.guard';

@Controller('api/article')
@UseGuards(JwtHttpGuard)
export class ArticleController {
  constructor(private readonly articleService: ArticleService) {}

  @Get('list')
  async findAll(): Promise<Article[]> {
    return await this.articleService.findAll();
  }

  @Get(':id')
  async findOne(@Param('id') id: string): Promise<Article | null> {
    const idNum = parseInt(id, 10);
    if (isNaN(idNum)) {
      throw new BadRequestException('Invalid article ID');
    }
    return await this.articleService.findOne(idNum);
  }

  @Get('category/:categoryId')
  async findByCategory(@Param('categoryId') categoryId: string): Promise<Article[]> {
    const categoryIdNum = parseInt(categoryId, 10);
    if (isNaN(categoryIdNum)) {
      throw new BadRequestException('Invalid category ID');
    }
    return await this.articleService.findByCategory(categoryIdNum);
  }

  @Get('author/:authorId')
  async findByAuthor(@Param('authorId') authorId: string): Promise<Article[]> {
    const authorIdNum = parseInt(authorId, 10);
    if (isNaN(authorIdNum)) {
      throw new BadRequestException('Invalid author ID');
    }
    return await this.articleService.findByAuthor(authorIdNum);
  }

  @Post()
  async create(@Body() articleData: Partial<Article>): Promise<Article> {
    return await this.articleService.create(articleData);
  }

  @Put(':id')
  async update(@Param('id') id: string, @Body() articleData: Partial<Article>): Promise<Article | null> {
    const idNum = parseInt(id, 10);
    if (isNaN(idNum)) {
      throw new BadRequestException('Invalid article ID');
    }
    return await this.articleService.update(idNum, articleData);
  }

  @Delete(':id')
  async remove(@Param('id') id: string): Promise<void> {
    const idNum = parseInt(id, 10);
    if (isNaN(idNum)) {
      throw new BadRequestException('Invalid article ID');
    }
    return await this.articleService.remove(idNum);
  }

  @Post(':id/publish')
  async publish(@Param('id') id: string): Promise<Article | null> {
    const idNum = parseInt(id, 10);
    if (isNaN(idNum)) {
      throw new BadRequestException('Invalid article ID');
    }
    return await this.articleService.publish(idNum);
  }

  @Post(':id/unpublish')
  async unpublish(@Param('id') id: string): Promise<Article | null> {
    const idNum = parseInt(id, 10);
    if (isNaN(idNum)) {
      throw new BadRequestException('Invalid article ID');
    }
    return await this.articleService.unpublish(idNum);
  }
}